package com.hxzy.config;

import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.exception.ShopException;
import com.hxzy.common.vo.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * springmvc 全局异常处理的类
 *
 * @author tonneyyy
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BindException.class)
    public R bindingResult(BindException bindException){
        log.error(bindException);
        List<ObjectError> allErrors = bindException.getAllErrors();
        String msg=allErrors.get(0).getDefaultMessage();
        R r= R.build(AckCode.FAIL);
        r.setMsg(msg);
        return r;
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public R serviceException(ServiceException e){
        log.error(e);
        R r= R.build(e.getAckCode());
        return r;
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ShopException.class)
    public R shopException(ShopException e){
        log.error(e);
        R r= R.build(AckCode.FAIL);
        r.setMsg(e.getMessage());
        return r;
    }


    /**
     * spring security没有权限访问
     * @param e
     * @return
     */
    @ExceptionHandler(value =AccessDeniedException.class )
    public R  accessDeniedException(AccessDeniedException  e){
        log.error(e);
        R r = R.build(AckCode.PERMISSION_NOT_ACCESS);
        return r;
    }
}
